﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;


namespace Epam.PeopleModel
{
    public class BirthDateAgeLimitAttribute:ValidationAttribute,IClientValidatable,IMetadataAware
    {
        public int AgeLimit { get; set; }

        public override bool IsValid(object value)
        {
            if (value == null) return true;
            var date = (DateTime)value;
            return date.Year <= DateTime.Now.Year - AgeLimit;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule=  new ModelClientValidationRule
                           {
                               ErrorMessage = ErrorMessage,
                               ValidationType = "birdthdatedgedimitval"
                           };
            rule.ValidationParameters["agelimit"] = AgeLimit.ToString();
            rule.ValidationParameters["nowdate"] = DateTime.Now.ToString("yyyy-MM-dd");
            yield return rule;
        }

        public void OnMetadataCreated(ModelMetadata metadata)
        {
            metadata.DataTypeName = "Date";
        }
    }
}
